//
//  MusicListViewController.m
//  MyMusic
//
//  Created by mac on 2019/4/12.
//  Copyright © 2019 YangYang. All rights reserved.
//

#import "MusicListViewController.h"
#import "MusicListTableViewCell.h"
#import "MusicPlayingViewController.h"
#import "WorksPathModel.h"
#import "DownloadView.h"

@interface MusicListViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *songListArr;

@property (nonatomic, assign) NSInteger downInteger;
@property (nonatomic, strong) NSArray *images;


@property (nonatomic, strong) DownloadView *downloadView;

@end

@implementation MusicListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _images = @[@{@"singerImageName":@"1.jpg",@"ablumImageName":@"album_1.jpg"},
                @{@"singerImageName":@"2.jpg",@"ablumImageName":@"album_2.jpg"},
                @{@"singerImageName":@"3.jpg",@"ablumImageName":@"album_3.jpg"},
                @{@"singerImageName":@"0.jpg",@"ablumImageName":@"album_0.jpg"}];
    
    
    _downInteger = 0;
    self.view.backgroundColor = [UIColor whiteColor];
    [self initTableView];
    switch (_worksPathModel.type) {
        case WorksSourceTypeNet:
        {
            [self initNetDataSource];
            NSString *downloadFilePath = DownloadFilePath(_worksPathModel.downloadSongFileFolderPath);
            if ([self getAllFileFromFolder:downloadFilePath].count >= self.songListArr.count) {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(deleteFileAction)];
            }
            else
            {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"下载" style:UIBarButtonItemStylePlain target:self action:@selector(downloadFileAction)];
            }
            
            
        }
            break;
        case WorksSourceTypeLocal:
        {
//            self.songListArr addObjectsFromArray:<#(nonnull NSArray *)#>;
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(deleteFileAction)];
            [self initLocalDataSource];
        }
            break;
            
        default:
            break;
    }
    
    
}

-(NSArray *)getAllFileFromFolder:(NSString *)folderPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:folderPath]) {
        NSError *error = nil;
        NSArray *fileArr = [fileManager contentsOfDirectoryAtPath:folderPath error:&error];
        return fileArr;
    }
    return [NSArray new];
}

-(void)downloadFileAction
{
    
    NSString *downloadFilePath = DownloadFilePath(_worksPathModel.downloadSongFileFolderPath);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    if (![fileManager fileExistsAtPath:downloadFilePath isDirectory:&isDir]) {
        [fileManager createDirectoryAtPath:downloadFilePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    if (self.songListArr.count > 0) {
        self.downloadView.text = [NSString stringWithFormat:@"%ld",self.downInteger + 1];
        if (self.downInteger > self.songListArr.count) {
            NSLog(@"下载超出数组范围，请检查代码");
            return;
        }
        
        self.navigationItem.rightBarButtonItem.enabled = NO;
        
        if (!_downloadView) {
            _downloadView = [[DownloadView alloc] initWithFrame:CGRectMake(kScreenWidth - 100, 100, 100, 100)];
            [[[UIApplication sharedApplication] keyWindow] addSubview:_downloadView];
            _downloadView.backgroundColor = [UIColor grayColor];
            _downloadView.layer.cornerRadius = 50;
            _downloadView.layer.masksToBounds = YES;
            
        }
        AlbumModel *model = self.songListArr[_downInteger];
        [self download:model.songPath andSaveDownloadFileName:DownloadFilePath(model.downloadFolderName)];
    }
}

- (void)WantToGoBackMianThread:(id)object{
    //需要在主线程执行的代码
    NSNumber *progressObject = (NSNumber *)object;
    CGFloat progress = [progressObject floatValue];
    self.downloadView.progress = progress;
}

- (void)download:(NSString *)downloadURL andSaveDownloadFileName:(NSString *)saveFileName{
    
    __weak typeof(self) weakSelf = self;
    
    NSString *fileName = [downloadURL lastPathComponent];
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@",saveFileName,fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    if ([fileManager fileExistsAtPath:fullPath isDirectory:&isDir]) {
        NSLog(@"文件已存在，下载下一个");
        weakSelf.downInteger++;
        NSLog(@"正在下载第%ld个文件",weakSelf.downInteger);
        if (weakSelf.downInteger < self.songListArr.count) {
//            NSString *downloadFilePath = DownloadFilePath(weakSelf.worksPathModel.worksName);
            AlbumModel *model = self.songListArr[weakSelf.downInteger];
            [weakSelf download:model.songPath andSaveDownloadFileName:DownloadFilePath(model.downloadFolderName)];
            self.downloadView.text = [NSString stringWithFormat:@"%ld",weakSelf.downInteger + 1];
        }
        else
        {
            [weakSelf downloadFinished];
        }
        return;
    }
    
    
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    NSString *videoURL = [downloadURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *url = videoURL;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    
    NSURLSessionDownloadTask *loadTask = [manger downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"Progress:----%.2f",100.0*downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);
        CGFloat progress = (downloadProgress.completedUnitCount * 1.0)/downloadProgress.totalUnitCount;
        [weakSelf performSelectorOnMainThread:@selector(WantToGoBackMianThread:) withObject:[NSNumber numberWithFloat:progress] waitUntilDone:YES];
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        NSString *fileName = response.suggestedFilename;
        NSString *fullPath = [NSString stringWithFormat:@"%@/%@",saveFileName,fileName];
        
        NSLog(@"下载路径：fullPath = %@",fullPath);
        
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"filePath:%@",filePath);
        weakSelf.downInteger++;
        NSLog(@"正在下载第%ld个文件",weakSelf.downInteger);
        if (weakSelf.downInteger < self.songListArr.count) {
//            NSString *downloadFilePath = DownloadFilePath(weakSelf.worksPathModel.worksName);
            AlbumModel *model = self.songListArr[weakSelf.downInteger];
            [weakSelf download:model.songPath andSaveDownloadFileName:DownloadFilePath(model.downloadFolderName)];
            self.downloadView.text = [NSString stringWithFormat:@"%ld",weakSelf.downInteger + 1];
        }
        else
        {
            [weakSelf downloadFinished];
        }
    }];
    [loadTask resume];
}

-(void)downloadFinished
{
    self.navigationItem.rightBarButtonItem.enabled = YES;
    _downloadView.text = @"下载完成";
    [_downloadView removeFromSuperview];
    _downloadView = nil;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(deleteFileAction)];
    self.downInteger = 0;
}

-(void)deleteFileAction
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确认删除文件？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self deleteFile];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

-(void)deleteFile
{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    NSString *downloadFilePath = DownloadFilePath(self.worksPathModel.downloadSongFileFolderPath);
    NSString *fullPath = [NSString stringWithFormat:@"%@",downloadFilePath];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:fullPath]) {
//        GGLog(@"文件已存在，删除文件");
        if ([manager removeItemAtPath:fullPath error:nil]) {
//            GGLog(@"文件已成功删除");
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(downloadFileAction)];
            [self.songListArr removeAllObjects];
            [self.tableView reloadData];
            
            if ([manager fileExistsAtPath:OtherOpenFilePath]) {
                NSMutableArray *otherFolderArr = [NSMutableArray arrayWithContentsOfFile:OtherOpenFilePath];
                NSMutableArray *tempArr = [NSMutableArray arrayWithArray:otherFolderArr];
                for (id object in tempArr) {
                    if ([object isKindOfClass:[NSDictionary class]]) {
                        NSDictionary *folderDic = (NSDictionary *)object;
                        if ([folderDic[@"folderName"] isEqualToString:[downloadFilePath lastPathComponent]]) {
                            [otherFolderArr removeObject:folderDic];
                        }
                    }
                    
                }
                if ([otherFolderArr writeToFile:OtherOpenFilePath atomically:YES]) {
                    NSLog(@"文件更新成功");
                }
                else
                {
                    NSLog(@"文件更新失败");
                }
            }
            
            
            [self.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:ChangeMusicListNotification object:nil];
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"removeItemNotification" object:nil userInfo:@{@"songName":[downloadFilePath lastPathComponent]}];
        }
        else
        {
//            GGLog(@"文件删除失败");
        }
    }
    NSLog(@"启用按钮");
    self.navigationItem.rightBarButtonItem.enabled = YES;
    self.downInteger = 0;
}

-(void)initNetDataSource
{
    NSString *localPathString = [[NSBundle mainBundle] pathForResource:_worksPathModel.worksPath ofType:@"" inDirectory:@"NetSource"];
    NSArray *localPathArr = [[NSArray alloc] initWithContentsOfFile:localPathString];
    
    for (NSDictionary *musicDic in localPathArr) {
        AlbumModel *model = [[AlbumModel alloc] init];
        model.songName = musicDic[@"musicName"];
        model.songExtensionName = musicDic[@"extensionName"];
        model.songPath = musicDic[@"songPath"];
        model.type = _worksPathModel.type;
        model.downloadFolderName = _worksPathModel.downloadSongFileFolderPath;
        model.albumName = musicDic[@"albumName"];
        model.singerName = musicDic[@"singerName"];
        model.albumImage = musicDic[@"albumImage"];
        model.singerImage = musicDic[@"singerImage"];
        model.videoURL = musicDic[@"videoURL"];
        
        [self.songListArr addObject:model];
    }
    [self.tableView reloadData];
}

-(void)initLocalDataSource
{
    
    NSArray *songArr = _worksPathModel.localSongs;
    
    for (NSDictionary *musicDic in songArr) {

        AlbumModel *model = [[AlbumModel alloc] init];
        NSString *songName = musicDic[@"musicName"];
        NSString *songExtensionName = musicDic[@"extensionName"];
        model.songName = songName;
        model.songExtensionName = songExtensionName;
        NSString *songPath = [LibraryFolder stringByAppendingPathComponent:musicDic[@"songPath"]];
        model.songPath = songPath;
        model.type = WorksSourceTypeLocal;
        model.downloadFolderName = [musicDic[@"songPath"] stringByDeletingLastPathComponent];
        model.albumImage = musicDic[@"albumImage"];
        model.singerImage = musicDic[@"singerImage"];
        [self.songListArr addObject:model];
    }
    [self.tableView reloadData];
}

-(void)initTableView
{
    PlayerBottomView *bottomView = [PlayerBottomView shareInstance];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - CGRectGetHeight(bottomView.frame)) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerClass:[MusicListTableViewCell class] forCellReuseIdentifier:@"MusicListTableViewCell"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MusicListTableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    AlbumModel *model = self.songListArr[indexPath.row];
    cell.musicListModel = model;
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.songListArr.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AlbumModel *model = self.songListArr[indexPath.row];
//    MusicPlayingViewController *musicPlayingVC = [[MusicPlayingViewController alloc] init];
    MusicPlayingViewController *musicPlayingVC = [MusicPlayingViewController sharedInstance];
    musicPlayingVC.navigationItem.title = model.songName;
    musicPlayingVC.playListModels = self.songListArr;
    musicPlayingVC.currentPlayIndex = indexPath.row;
    [musicPlayingVC play:model];
    [self.navigationController pushViewController:musicPlayingVC animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

-(NSMutableArray *)songListArr
{
    if (!_songListArr) {
        _songListArr = [NSMutableArray new];
    }
    return _songListArr;
}

//-(UILabel *)downloadView
//{
//    if (!_downloadView) {
//        _downloadView = [[UILabel alloc] init];
//    }
//    return _downloadView;
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
